﻿using AlarmClock.BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace AlarmClock.UI.Forms
{
    public partial class FrmUpdateMusicList : Form
    {
        //添加音乐列表
        private string sourse_audioPath;
        private List<Audio> audios;
        //铃声播放器
        private PPNAudio myNAudio;

        OpenFileDialog ofg_AddMusic = new OpenFileDialog()
        {
            InitialDirectory = "D:\\",
            Filter = "支持播放的音乐文件|*.mp3;*.flac;*.wav;*.ape;*.aiff;*.ogg;*.midi;*.acc;",
            Multiselect = true,
            Title = "选择要添加的音乐文件（可按下shift+鼠标左键拖动多选）",
            RestoreDirectory = true
        };

        FolderBrowserDialog fbd_AddMusicFolder = new FolderBrowserDialog()
        {
            SelectedPath = "D:\\",
            Description = "选择要添加的音乐文件目录",            
        };

        public FrmUpdateMusicList(List<Audio> audios,string sourse_audioPath)
        {
            InitializeComponent();

            ContextMenuStrip Music_RightMouse_Menu = new ContextMenuStrip(); 
            ToolStripMenuItem del_MenuItem = new ToolStripMenuItem("删除");
            del_MenuItem.Click += (s, e) =>
            {
                if (MessageBox.Show($"是否要删除已选择的文件？","删除") == DialogResult.OK)
                {
                    myNAudio?.Stop();
                    while (Music_ListBox.SelectedItems.Count > 0)
                    {
                        string item = Music_ListBox.SelectedItems[0] as string;
                        var audio = audios.Where(p => p.musicFileNameNoExten == item).FirstOrDefault();
                        if (audio != null)
                        {
                            try
                            {
                                File.Delete(audio.musicfullPath);
                                audios.Remove(audio);
                                Music_ListBox.Items.Remove(item);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"删除文件失败,删除操作中断。\r\n文件路径：{audio.musicfullPath} \r\n原因：{ex.Message}", "删除失败");
                                break;
                            }
                        }

                    }
                }
            };
            Music_RightMouse_Menu.Items.Add(del_MenuItem);
            this.Music_ListBox.ContextMenuStrip = Music_RightMouse_Menu;

            this.audios = audios;
            this.sourse_audioPath = sourse_audioPath;
            this.Music_ListBox.Items.Clear();
            this.Music_ListBox.Items.AddRange(audios.Select(p => p.musicFileNameNoExten).ToArray());

            this.btn_Exit.Click += btn_Click;
            this.btn_AddMusicFile.Click += btn_Click;
            this.btn_AddMusicDirectory.Click += btn_Click;

            this.FormClosing += (sender, e) => { myNAudio?.Stop(); };
        }

        private void btn_Click(object sender, EventArgs e)
        {
            var btn = (Button)sender;
            switch (btn.Name)
            {
                case "btn_Exit"://退出
                    this.Close();
                   
                    break;                

                case "btn_AddMusicFile"://添加文件
                    if (ofg_AddMusic.ShowDialog() == DialogResult.OK)
                    {
                        string[] paths = ofg_AddMusic.FileNames;
                        List<string> errorMusic=new List<string>();
                        foreach (string sourseFile in paths)
                        {
                            if (File.Exists(sourseFile))
                            {
                                //检查是否是支持的音乐格式
                                if (PPNAudio.CanPlay(sourseFile))
                                {
                                    var audio = new Audio() { musicfullPath = Path.Combine(sourse_audioPath, Path.GetFileName(sourseFile)) };
                                    File.Copy(sourseFile, audio.musicfullPath, true);
                                    if (!this.Music_ListBox.Items.Contains(audio.musicFileNameNoExten))
                                    {
                                        audios.Add(audio);
                                    }
                                }
                                else
                                {
                                    errorMusic.Add(sourseFile);//不支持播放的音乐
                                }
                            }
                        }
                        this.Music_ListBox.Items.Clear();
                        this.Music_ListBox.Items.AddRange(audios.Select(p => p.musicFileNameNoExten).ToArray());

                        if(errorMusic.Count>0)
                        {
                            MessageBox.Show(string.Join("\r\n", errorMusic), "检查到不能播放的音乐文件");
                        }
                    }

                    break;

                case "btn_AddMusicDirectory"://添加目录
                    if (fbd_AddMusicFolder.ShowDialog() == DialogResult.OK)
                    {
                        string folder_Path = fbd_AddMusicFolder.SelectedPath;
                        string[] paths = Directory.GetFiles(folder_Path, "*", SearchOption.AllDirectories);
                        List<string> errorMusic = new List<string>();
                        foreach (string sourseFile in paths)
                        {
                            if (File.Exists(sourseFile))
                            {
                                //检查是否是支持的音乐格式
                                if(PPNAudio.CanPlay(sourseFile))
                                {
                                    var audio = new Audio() { musicfullPath = Path.Combine(sourse_audioPath, Path.GetFileName(sourseFile)) };
                                    File.Copy(sourseFile, audio.musicfullPath, true);
                                    if (!this.Music_ListBox.Items.Contains(audio.musicFileNameNoExten))
                                    {
                                        audios.Add(audio);
                                    }
                                }
                                else
                                {
                                    errorMusic.Add(sourseFile);//不支持播放的音乐
                                }
                            }
                        }
                        this.Music_ListBox.Items.Clear();
                        this.Music_ListBox.Items.AddRange(audios.Select(p => p.musicFileNameNoExten).ToArray());

                        if (errorMusic.Count > 0)
                        {
                            MessageBox.Show(string.Join("\r\n", errorMusic), "检查到不能播放的音乐文件");
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        /// <summary>
        /// 选中播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void M_List_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Music_ListBox.SelectedIndex >= 0 && Music_ListBox.SelectedIndex < audios.Count)
            {
                var audio = audios[Music_ListBox.SelectedIndex];
                //音乐
                string musicPath = audio.musicfullPath;
                myNAudio?.Stop();
                myNAudio = new PPNAudio(musicPath);
                myNAudio?.Play();
            }
        }
    }
}
